import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import s from './style.module.css';
import AddYunaqBlacklist from '../../../../components/AddYunaqBlacklist';
import Label from '../../../../components/Label';
import { datetime } from '../../../../../common/formatter';
import fetch from 'API/fetch';
import { CONTENT_IDX_LABEL_MAP } from '../../../../../common/constants';
import Icon from '../../../Home/icon';
import Breadcrumb, { Item } from '../../../../components/Breadcrumb';
function DetailC({
	className,
	location: { sendState },
	match: {
		params: { taskId },
	},
}) {
	sendState && sessionStorage.setItem('state', JSON.stringify(sendState));
	const state = JSON.parse(sessionStorage.state);
	const [data, setData] = React.useState({ results: [] });
	const [hasDetails, setHasDetails] = React.useState(null);
	const getDate = async () => {
		const res = await fetch(
			`/api/v2/tasks/content/evidence?id=${state.taskId}&warningId=${state.id}`,
			{
				method: 'GET',
			}
		);
		if (res.code === 200) {
			setData(res.results);
			codeDetails(res.results);
		}
	};
	// 详情表 data.detail为老数据处理
	const tbodyContent = () => {
		const showText = (type, td, e) => {
			if (data.detail) {
				const obj = {
					敏感词: {
						td1: CONTENT_IDX_LABEL_MAP.keyword[e[0]],
						td2: e[1].join(','),
					},
					隐私信息: {
						td1: CONTENT_IDX_LABEL_MAP.privacy_disclosure[e[0]],
						td2: e[1],
					},
				};
				return obj[type][td];
			} else {
				const obj = {
					敏感词: {
						td1:
							CONTENT_IDX_LABEL_MAP.keyword[e.category] ||
							CONTENT_IDX_LABEL_MAP.keyword[e.type],
						td2: e.word ? e.word : e.keywords ? e.keywords.join(',') : '',
					},
					隐私信息: {
						td1: CONTENT_IDX_LABEL_MAP.privacy_disclosure[e.type],
						td2: e.content,
					},
				};
				return obj[type][td];
			}
		};
		let det = [];
		if (!data.results[0] && !data.detail) {
			return (
				<tbody>
					<tr className={s.row}>
						<td className={s.td1} colSpan="2">
							暂无数据
						</td>
					</tr>
				</tbody>
			);
		} else if (data.detail) {
			det = Object.entries(data.detail);
		} else {
			det = data.results;
		}
		return (
			<tbody>
				{det.map((e, i) => {
					return (
						<tr className={s.row} key={i}>
							<td className={s.td1}>{showText(state.title, 'td1', e)}</td>
							<td className={s.td2}>{showText(state.title, 'td2', e)}</td>
						</tr>
					);
				})}
			</tbody>
		);
	};
	// 源码显示
	const codeDetails = data => {
		const style = { color: '#fff', background: '#e70c0c' };
		let str = '';
		const dom = [];

		if (!data.results) {
			setHasDetails(null);
		}
		Object.values(data.results).forEach(item => {
			if (!item.evidences) {
				return false;
			}
			item.evidences.forEach(code => {
				str = code.split(item.word || item.content);
				dom.push(
					<p className={s.codeRow}>
						{str.map((e, i) => {
							if (i < str.length - 1) {
								return (
									<>
										<span>{e}</span>
										<span style={style}>{item.word || item.content}</span>
									</>
								);
							} else {
								return (
									<>
										<span>{e}</span>
										<p>......</p>
									</>
								);
							}
						})}
					</p>
				);
			});
		});

		if (dom[0]) {
			setHasDetails(
				<div>
					{dom.map(e => {
						return e;
					})}
				</div>
			);
		} else {
			setHasDetails(null);
		}
	};
	React.useMemo(() => {
		getDate();
	}, []);
	return (
		<div className={cn(className, s.detail)}>
			<Breadcrumb>
				<Item key="job-manage" disabled>
					任务管理
				</Item>
				<Item key="web-task">Web安全监测</Item>
				{state.isHistory ?
					<Item key={`history?asset_task_id=${state.atid}&task_id=${state.taskId}&task_types=content`}>历史任务</Item> :
					<Item key={`detail?id=${state.atid}&type=${state.taskType}&tag=content`}>监测详情</Item>
				}
				<Item key="">{state.title}详情</Item>
			</Breadcrumb>
			<div className={s.content}>
				<div className={s.cydEnabled}>
					{state.cydEnabled && (
						<AddYunaqBlacklist
							size="small"
							taskId={state.taskId}
							warningId={state.id}
						/>
					)}
				</div>
				<div className={s.content1}>
					<Label className={s.labelDetail}>详情信息</Label>
					<p>
						<span className={s.titleSpan}>风险地址：</span>
						{state.url}
					</p>
					<div className={s.tableBox}>
						<table className={s.table}>
							<thead>
								<tr className={s.head}>
									<td className={s.td1}>{state.title}类型</td>
									<td className={s.td2}>详情</td>
								</tr>
							</thead>
							{tbodyContent()}
						</table>
					</div>
				</div>
				<div className={s.content1}>
					<Label className={s.labelDetail}>风险地址源码</Label>
					<div>
						<span className={s.titleSpan}>抓取时间：</span>
						<span>
							{data && hasDetails !== null
								? datetime(data.foundAt) || '- -'
								: '- -'}
						</span>
					</div>
					<div className={s.showBox}>
						{hasDetails || (
							<div className={cn(s.empty)}>
								<Icon active="empty"></Icon>
								<span>暂无数据</span>
							</div>
						)}
					</div>
				</div>
			</div>
		</div>
	);
}

DetailC.propTypes = {
	className: PropTypes.string,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
	}).isRequired,
	location: PropTypes.any,
	match: PropTypes.shape({
		sendState: PropTypes.any,
		params: PropTypes.shape({
			taskId: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
	params: PropTypes.any,
};
DetailC.defaultProps = {
	className: '',
};

export default withRouter(DetailC);
